package com.jeequan.jeepay.pay.router.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.entity.MchPayPassage;
import com.jeequan.jeepay.core.entity.MchPayRoute;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.pay.model.MchAppConfigContext;
import com.jeequan.jeepay.pay.router.PassageInfo;
import com.jeequan.jeepay.pay.router.RouteStrategy;
import com.jeequan.jeepay.pay.rqrs.payorder.UnifiedOrderRQ;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 金额区间
 * 配置json格式为:
 * [{"start": 0, "end":100, "ifCode:"alipay"}]
 * start和end为>=和<，金额为元， -1表示无限
 *
 * @author wxj
 * 2024/10/25
 */
@Service
public class AmountRangeStrategy implements RouteStrategy {
    @Override
    public MchPayPassage route(MchAppConfigContext mchAppConfigContext, UnifiedOrderRQ bizRQ, MchPayRoute mchPayRoute, Map<String, PassageInfo> channelInfoMap) {
        JSONArray jsonArray = JSONArray.parseArray(mchPayRoute.getStrategyParams());
        double payAmount = Double.parseDouble(AmountUtil.convertCent2Dollar(bizRQ.getAmount().toString()));
        for (Object item : jsonArray) {
            JSONObject jsonObject = (JSONObject) item;
            double start = jsonObject.getDouble("start");
            double end = jsonObject.getDouble("end");
            if ((start == -1 || start <= payAmount)
                    && (end == -1 || payAmount < end)) {
                String ifCode = jsonObject.getString("ifCode");
                return channelInfoMap.get(ifCode).getMchPayPassage();
            }
        }
        return null;
    }
}
